package cn.wolfcode.wolf2w.interceptor;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.IUserInfoRedisService;
import cn.wolfcode.wolf2w.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
* 用户登录拦截实现
* 也可以贴@Component:Spring启动时扫描到component这个版型标签，并创建登录拦截器
* */

public class CheckLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {


        //排除跨域请求
        //instanceof判断左边对象变量是不是右边类的实例
        if(!(handler instanceof HandlerMethod)){
             return true;
        }

        //获取封装HandlerMethod的对象,里面封装了浏览器带来的(路径,方法名等信息)
        HandlerMethod hm = (HandlerMethod)handler;

        //获取浏览器发送的token数据
        String token = request.getHeader("token");
        //通过token获取redis中的value
        UserInfo user = userInfoRedisService.getUserInfo(token);

        //判断当前前期方法上面是否贴有注解,如果没有放行,如果有则提示请先登录
        if(hm.hasMethodAnnotation(RequireLogin.class)){
            if(user==null){
                //表示没有登录。提示用户重新登录,使用response.getWriter().writer（）输出到浏览器显示
                response.setContentType("application/json;charset=UTF-8");//json格式的中文转码
                response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
                return false;
            }
        }
        return true;
    }
}
